package com.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * 资源工具类,封装了一些Spring资源相关的方法
 * 
 * @author Administrator
 *
 */
public class ResourceUtils {
	
	private ResourceUtils(){}
	
	/**
	 * 根据传入的classpath路径查找资源
	 * @param locationPattern
	 * @return
	 */
	public static Resource[] getClassPathResourceByPattern(String locationPattern){
		return getClassPathResource(locationPattern, Thread.currentThread().getContextClassLoader());
	}
	/**
	 * 根据spring的模式进行匹配找到资源,支持多个匹配条件用逗号分开
	 * 
	 * @param locationPattern 模式表达式
	 * @param classLoader 指定类加载器
	 * 
	 * @return
	 */
	public static Resource[] getClassPathResource(String loacationPattern,ClassLoader classLoader){
		if(loacationPattern == null || classLoader == null){
			return new Resource[0];
		}
		ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(classLoader);
		List<Resource> list = new ArrayList<>();
		String[] patterns = loacationPattern.split(",");
		try {
			for (String string : patterns) {
				Resource[] resources = patternResolver.getResources(string);
				if(resources != null && resources.length >= 1){
					list.addAll(Arrays.asList(resources));
				}
			}
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		return list.toArray(new Resource[list.size()]);
	}
	
	/**
	 * 将获取到的资源转换成集合
	 * @param loacationPattern
	 * @param classLoader
	 * @return
	 */
	public static Collection<Resource> getClassPathResourceToCollection(String loacationPattern,ClassLoader classLoader){
		Resource[] resources = getClassPathResource(loacationPattern, classLoader);
		if(CollectionUtils.notEmpty(resources)){
			return Arrays.asList(resources);
		}
		return new ArrayList<Resource>();
	}
	

}
